// GenBooks.cpp : implementation file
//

#include <stdafx.h>
#include "SwordBible.h"
#include "GenBooks.h"
#include "SwordBibleDoc.h"
#include "ColorMgr.h"
#include "BibleForm.h"

// CGenBooks dialog

int CGenBooks::active;
CSwordBibleFonts CGenBooks::font;
CString CGenBooks::ActiveMainFrameCommand;

IMPLEMENT_DYNAMIC(CGenBooks, CPropertyPage)

CGenBooks::CGenBooks()
	: CPropertyPage(CGenBooks::IDD)
{
	active = 0;
	pModule = NULL;

}

CGenBooks::~CGenBooks()
{
		
}

void CGenBooks::DoDataExchange(CDataExchange* pDX)
{
	CPropertyPage::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_RICHEDIT_GENBOOKS, m_rich);
	DDX_Control(pDX, IDC_TREE_BOOKINDEX, m_tree);

}


BEGIN_MESSAGE_MAP(CGenBooks, CPropertyPage)
	ON_WM_SIZE()
	ON_COMMAND(ID_GENBOOKS_VERSIONS, OnShowVersions)	
	ON_COMMAND(ID_GENBOOKS_PRINT,OnPrint)
	ON_COMMAND(ID_GENBOOKS_SELECTALL, OnSelectAll)
	ON_COMMAND(ID_GENBOOKS_COPY, OnCopy)
	ON_COMMAND(ID_GENBOOKS_FONT, OnFont)
	ON_COMMAND(ID_GENBOOKS_ZOOM, OnZoom)
	ON_UPDATE_COMMAND_UI(ID_GENBOOKS_ZOOM, OnUpdateZoom)
	ON_COMMAND(ID_GENBOOKS_NEXT,OnNext)
	ON_COMMAND(ID_GENBOOKS_PREVIOUS,OnPrevious)

	ON_MESSAGE(ID_GENBOOKS_COMMAND, OnMainFrameCommand)

	ON_NOTIFY_EX_RANGE(TTN_NEEDTEXTW, 0, 0xFFFF, OnToolTipNotify)
    ON_NOTIFY_EX_RANGE(TTN_NEEDTEXTA, 0, 0xFFFF, OnToolTipNotify)   

	ON_NOTIFY(EN_MSGFILTER, IDC_RICHEDIT_GENBOOKS, &CGenBooks::OnEnMsgfilterGenbooks)
	ON_NOTIFY(TVN_SELCHANGED, IDC_TREE_BOOKINDEX, &CGenBooks::OnTvnSelchangedTree)
END_MESSAGE_MAP()


// CGenBooks message handlers


void CGenBooks::OnSize(UINT nType, int cx, int cy)
{
	CPropertyPage::OnSize(nType, cx, cy);

	if(::IsWindow(m_rich.GetSafeHwnd()) ) 
		m_rich.SetWindowPos(NULL,10,40,cx- 330,cy-50,SWP_NOZORDER | SWP_NOACTIVATE);
	
	if(::IsWindow(m_tree.GetSafeHwnd())  ) 
	    m_tree.SetWindowPos(NULL, cx - 310 ,40, 300,cy-50,SWP_NOZORDER | SWP_NOACTIVATE);
	

	
}

BOOL CGenBooks::OnInitDialog()
{
	CPropertyPage::OnInitDialog();

	

	

	// load the font of the page display
	font.location = AFX_GENBOOKS; 
	font.Load();
	font.ConstructRTF();
	m_rich.SetBackgroundColor(FALSE, CColorMgr::RTFtoCOLORREF(font.bg_color) );

	// to receive the mouseevents
	m_rich.SetEventMask(ENM_MOUSEEVENTS | ENM_KEYEVENTS | ENM_SCROLLEVENTS);
	m_rich.SendMessage(EM_EXLIMITTEXT,0,-1);

		
	LoadToolbar();

	HICON icon_folder = ::AfxGetApp()->LoadIcon(IDI_ICON_FOLDER);
	m_image.Create(16,16, ILC_COLORDDB ,0,1);
	m_image.SetBkColor(RGB(255,255,255));
	m_image.Add(icon_folder);
		

	m_tree.SetImageList(&m_image, TVSIL_NORMAL );

	if(CSwordBibleDoc::numGenBooksAvailable > 0) 
	{
		active = 0;
		pModule = CSwordBibleDoc::pRTFGenBooks[active];
		PopulateTree();
		
	}


	return TRUE;  // return TRUE unless you set the focus to a control
	// EXCEPTION: OCX Property Pages should return FALSE
}

// this function loads the toolbar on the bible page
int CGenBooks::LoadToolbar(void)
{
	
  if (!m_wndFormatBar.CreateEx(this, TBSTYLE_FLAT, WS_CHILD
       | WS_VISIBLE | CBRS_TOP |  CBRS_FLYBY | CBRS_TOOLTIPS) ||
       !m_wndFormatBar.LoadToolBar(IDR_GENBOOKS_TOOLBAR))
   {
      TRACE0("Failed to create toolbar\n");
      return -1;      // fail to create
   }

   // buttons size: 16
   // bitmaps:
   // enabled - IDB_TOOLBAR_NORMAL
   // hovered - IDB_TOOLBAR_HOT
   // disabled - IDB_TOOLBAR_DISABLED
   // transparent color RGB(255, 0, 255)
   m_wndFormatBar.LoadTCToolBar(24, IDB_BITMAP_GENBOOKS, IDB_BITMAP_GENBOOKS,
                              IDB_BITMAP_GENBOOKS, RGB(255,255,255));




	// Position the control bars using RepositionBars. 
	RepositionBars(AFX_IDW_CONTROLBAR_FIRST, AFX_IDW_CONTROLBAR_LAST, 0);

	// Expand the size of the Toolbar window so all controls in it would fit
	
	CRect toolBarRect;
	CToolBarCtrl& formatBar = m_wndFormatBar.GetToolBarCtrl();
	formatBar.GetWindowRect(toolBarRect);
	ScreenToClient(toolBarRect);
	toolBarRect.left += 10  ;
	toolBarRect.right += 500  ;
	formatBar.MoveWindow(toolBarRect,TRUE);

	return 0;
}

void CGenBooks::PopulateTree()
{
	
		m_tree.SetRedraw(FALSE);

		m_tree.DeleteAllItems();
		

	
		if (!pModule) // check that pointer is not NULL
		{
			m_tree.SetRedraw(TRUE);
			return; 
		}

		 pModule->setPosition(sword::TOP);
		 CSwordBibleDoc::GenBookTree =  (sword::TreeKeyIdx *) pModule->getKey();
		 CSwordBibleDoc::GenBookTree->root();
		 CSwordBibleDoc::GenBookTree->firstChild();
	
		 HTREEITEM item = m_tree.InsertItem((CString) CSwordBibleDoc::GenBookTree->getLocalName() ,0,0); // root item
		 AddTreeItem(item);   // recursive function

		  m_tree.SetRedraw(TRUE);

		  m_tree.Select( m_tree.GetRootItem(), TVGN_CARET);
		
}

// Add a child item or sibling
void CGenBooks::AddTreeItem(HTREEITEM item)
{
	
	if(CSwordBibleDoc::GenBookTree->firstChild() )
	{
		tempStr = CSwordBibleDoc::GenBookTree->getLocalName();
		tempStr.Replace(_T("’"),_T("'"));
		item = m_tree.InsertItem( tempStr,0,0, item);
		AddTreeItem(item); 
		CSwordBibleDoc::GenBookTree->parent();
		item = m_tree.GetParentItem(item);
		
	}

	if(CSwordBibleDoc::GenBookTree->nextSibling() )
	{
		tempStr = CSwordBibleDoc::GenBookTree->getLocalName();
		tempStr.Replace(_T("’"),_T("'"));
		item = m_tree.InsertItem(tempStr ,0,0, m_tree.GetParentItem(item) );
		AddTreeItem(item);
	
	}

}

void CGenBooks::ShowChapter()
{
	if(!pModule) return;

	
	pModule->SetKey(CSwordBibleDoc::GenBookKey);

	chapText = font.GetHeaderRTF();

	
	CString titleSize;
	titleSize.Format(_T("\\cf2\\fs%d "), font.text_facesize + 5);
	chapText = chapText +  titleSize + (CString) pModule->Name() + (CString) CSwordBibleDoc::GenBookKey.getText();
		

	// reset the font size
	titleSize.Format(_T("\\fs%d "), font.text_facesize);
	chapText = chapText +  titleSize + _T("\\par\\par ");

	CString renderText = (CString) pModule->RenderText();

	chapText += renderText;

	chapText += _T("}"); 

	chapText.Replace(_T("’"), _T("'"));
	
	if(CSwordBibleDoc::crossref_tags)
	{
		chapText.Replace(_T("<a href=\"\">"),  _T("<a href=\"\">\\cf6\\b "));
		chapText.Replace(_T("</a>"), _T("</a>\\cf2\\b0 "));
	}

	else
	{
		chapText.Replace(_T("<a href=\"\">"),  _T(""));
		chapText.Replace(_T("</a>"), _T("") );
	}

	

	m_rich.SetRTF(chapText);

}

void CGenBooks::OnShowVersions()
{
	RECT rc;
    m_wndFormatBar.GetToolBarCtrl().GetItemRect(0,&rc);
	m_wndFormatBar.ClientToScreen(&rc); // TrackPopupMenu uses screen coords

   CMenu menu;
   menu.CreatePopupMenu();
   CMenu* pPopup = NULL;
   pPopup = &menu;

   if(pPopup == NULL) return;
   int dwSelectionMade;  

 
   // fill in the strings for different commentary versions
	for(int i = 0; i < CSwordBibleDoc::numGenBooksAvailable; i++)
		if(CSwordBibleDoc::pRTFGenBooks[i] != NULL)
		{
			         pPopup->AppendMenu(MF_STRING,ID_GENBOOK_NAMES + i, (CString) CSwordBibleDoc::pRTFGenBooks[i]->Description());
					 if(active == i) pPopup->CheckMenuItem(ID_GENBOOK_NAMES + i,MF_CHECKED); 

		}


         dwSelectionMade =  pPopup->TrackPopupMenu(TPM_LEFTALIGN | TPM_LEFTBUTTON|TPM_RETURNCMD, 
         rc.left, rc.bottom + 4, this);

	
		int selection = dwSelectionMade;
		int base = ID_GENBOOK_NAMES;
		int temp = selection - base;

	if(temp >= 0 && temp < CSwordBibleDoc::numGenBooksAvailable) 
	{
		 active = temp;
	     pModule = CSwordBibleDoc::pRTFGenBooks[active];
	     PopulateTree();

		 
	}

    pPopup->DestroyMenu();


}

void CGenBooks::OnPrint()
{
		// only the active page should handle the message
		if(  !( ((CPropertySheet*) GetParent())->GetActivePage()   == this) )  
	  return;

	

	CBibleForm::pControl = (CRichEditCtrl *) GetDlgItem(IDC_RICHEDIT_GENBOOKS);
		AfxGetMainWnd()->SendMessageToDescendants(WM_PRINT_CONTROL, (WPARAM) 1 , 0);

}

void CGenBooks::OnCopy()
{
		// only the active page should handle the message
		 if(  !( ((CPropertySheet*) GetParent())->GetActivePage()   == this) )  
		return;

		 
		m_rich.Copy();

}

void CGenBooks::OnSelectAll()
{

		// only the active page should handle the message
		if(  !( ((CPropertySheet*) GetParent())->GetActivePage()   == this) )  
		return;

		m_rich.SetFocus();
		m_rich.SetSel(0,-1);

}

void CGenBooks::OnFont()
{
	
		// only the active page should handle the message
		if(  ((CPropertySheet*) GetParent())->GetActivePage()   != this) return;

		CColorMgr colordlg(NULL, &font);

		 if(colordlg.DoModal() == IDOK)
  		{
			m_rich.SetBackgroundColor(false, CColorMgr::RTFtoCOLORREF(font.bg_color) );
			ShowChapter();
		}

}

void CGenBooks::OnZoom()
{
	// only the active page should handle the message
		if(  !( ((CPropertySheet*) GetParent())->GetActivePage()   == this) )  
	  return;



	CSwordBibleDoc::GenBookZoom = !(CSwordBibleDoc::GenBookZoom);
	ZoomText();


}

void CGenBooks::OnUpdateZoom(CCmdUI *pCmdUI)
{
	

	pCmdUI->SetCheck(CSwordBibleDoc::GenBookZoom);

}

void CGenBooks::ZoomText()
{
	// only the active page should handle the message
		if(  !( ((CPropertySheet*) GetParent())->GetActivePage()   == this) )  
	  return;
	
	if(CSwordBibleDoc::GenBookZoom) m_rich.SendMessage(EM_SETZOOM, 5,4); //zoom by 1.25
	else m_rich.SendMessage(EM_SETZOOM, 0,0);  // turn off zooming
	

}

void CGenBooks::OnPrevious()
{
	// only the active page should handle the message
		if(  !( ((CPropertySheet*) GetParent())->GetActivePage()   == this) )  
	  return;

		if(!pModule) return;

		pModule->SetKey(CSwordBibleDoc::GenBookKey);	
		pModule->decrement(1);

		sword::SWKey* temp = NULL;
		temp = pModule->getKey();

		if(temp == NULL || temp->Error() ) return;

		CSwordBibleDoc::GenBookKey = *temp;

		ShowChapter();

	

}

void CGenBooks::OnNext()
{
	// only the active page should handle the message
		if(  !( ((CPropertySheet*) GetParent())->GetActivePage()   == this) )  
	  return;

		if(!pModule) return;

		pModule->SetKey(CSwordBibleDoc::GenBookKey);	
		pModule->increment(1);

		sword::SWKey* temp = NULL;
		temp = pModule->getKey();

		if(temp == NULL || temp->Error() ) return;

		CSwordBibleDoc::GenBookKey = *temp;

		ShowChapter();



}


void CGenBooks::OnEnMsgfilterGenbooks(NMHDR *pNMHDR, LRESULT *pResult)
{
	MSGFILTER *pMsgFilter = reinterpret_cast<MSGFILTER *>(pNMHDR);
	
	if (pMsgFilter->msg == WM_RBUTTONDOWN)   OnRightButtonDown();

	*pResult = 0;
}

void CGenBooks::OnRightButtonDown()
{
	

	 CPoint point;                                            
     ::GetCursorPos(&point); //where is the mouse?
     CMenu menu; //lets display out context menu :) 
     DWORD dwSelectionMade;                                       
     VERIFY(menu.LoadMenu(_T("IDR_MENU_GENBOOKS")) );  
     CMenu *pmenuPopup = menu.GetSubMenu(0);
     ASSERT(pmenuPopup != NULL);   

	 if(CSwordBibleDoc::GenBookZoom)	pmenuPopup->CheckMenuItem(ID_GENBOOKS_ZOOM,MF_CHECKED); 
	

     dwSelectionMade = pmenuPopup->TrackPopupMenu( (TPM_LEFTALIGN|TPM_LEFTBUTTON|
                                                      TPM_RETURNCMD),
                                                    point.x, point.y, this); 

	

	
	switch (dwSelectionMade)
	{
	case ID_GENBOOKS_PRINT:		   OnPrint(); break;
	case ID_GENBOOKS_COPY:		   OnCopy(); break;
	case ID_GENBOOKS_SELECTALL:    OnSelectAll(); break;
	case ID_GENBOOKS_FONT:		   OnFont(); break;    
	case ID_GENBOOKS_ZOOM:         OnZoom(); break; 
	case ID_GENBOOKS_PREVIOUS:	   OnPrevious(); break;
	case ID_GENBOOKS_NEXT:         OnNext(); break;

	}

	
	pmenuPopup->DestroyMenu(); 



}


BOOL CGenBooks::OnToolTipNotify(UINT id, NMHDR *pNMHDR,   LRESULT *pResult)
{
    ASSERT(pNMHDR->code == TTN_NEEDTEXTA || pNMHDR->code == TTN_NEEDTEXTW);

     // if there is a top level routing frame then let it handle the message
     if (GetRoutingFrame() != NULL) return FALSE;

     // to be thorough we will need to handle UNICODE versions of the message also !!
     TOOLTIPTEXTA* pTTTA = (TOOLTIPTEXTA*)pNMHDR;
     TOOLTIPTEXTW* pTTTW = (TOOLTIPTEXTW*)pNMHDR;
     TCHAR szFullText[512];
     CString strTipText;
     UINT nID = pNMHDR->idFrom;

     if (pNMHDR->code == TTN_NEEDTEXTA && (pTTTA->uFlags & TTF_IDISHWND) ||
         pNMHDR->code == TTN_NEEDTEXTW && (pTTTW->uFlags & TTF_IDISHWND))
     {
          // idFrom is actually the HWND of the tool 
          nID = ::GetDlgCtrlID((HWND)nID);
     }

     if (nID != 0) // will be zero on a separator
     {
          AfxLoadString(nID, szFullText);
          strTipText=szFullText;

#ifndef _UNICODE
          if (pNMHDR->code == TTN_NEEDTEXTA)
          {
               lstrcpyn(pTTTA->szText, strTipText, sizeof(pTTTA->szText));
          }
          else
          {
               _mbstowcsz(pTTTW->szText, strTipText, sizeof(pTTTW->szText));
          }
#else
          if (pNMHDR->code == TTN_NEEDTEXTA)
          {
               _wcstombsz(pTTTA->szText, strTipText,sizeof(pTTTA->szText));
          }
          else
          {
               lstrcpyn(pTTTW->szText, strTipText, sizeof(pTTTW->szText));
          }
#endif

          *pResult = 0;

          // bring the tooltip window above other popup windows
          ::SetWindowPos(pNMHDR->hwndFrom, HWND_TOP, 0, 0, 0, 0,SWP_NOACTIVATE|
               SWP_NOSIZE|SWP_NOMOVE|SWP_NOOWNERZORDER); return TRUE;
     }

     return FALSE;
}



LONG CGenBooks::OnMainFrameCommand(UINT, LONG)
{ 
	
	// only the active page should handle the message
	  if(  !( ((CPropertySheet*) GetParent())->GetActivePage()   == this) )  
	  return 0L;
	
	if (ActiveMainFrameCommand ==  _T("print"))		        OnPrint();
	else if (ActiveMainFrameCommand == _T("copy"))			OnCopy();
	else if (ActiveMainFrameCommand == _T("selectall"))     OnSelectAll();
	else if (ActiveMainFrameCommand == _T("display"))       OnFont();
	else if (ActiveMainFrameCommand == _T("zoom"))          OnZoom();
	else if (ActiveMainFrameCommand == _T("previous"))		OnPrevious();
	else if (ActiveMainFrameCommand == _T("next"))          OnNext();

	
	return 0L;

}



void CGenBooks::OnTvnSelchangedTree(NMHDR *pNMHDR, LRESULT *pResult)
{
	

	LPNMTREEVIEW pNMTreeView = reinterpret_cast<LPNMTREEVIEW>(pNMHDR);
	// TODO: Add your control notification handler code here

	HTREEITEM item = m_tree.GetSelectedItem();

	if(item == NULL) return;

	
	CString text = _T("");
	
	
	while(item)
	{
		text = _T("/") +  m_tree.GetItemText(item) + text;
		item = m_tree.GetParentItem(item);
	}


	CSwordBibleDoc::GenBookKey = (CStringA) text;



	ShowChapter();

	*pResult = 0;
}
